package uia.alumni.useradm;

import java.io.PrintWriter;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import uia.alumni.data.Role;
import uia.alumni.data.User;
import uia.alumni.web.Page;



/**
 *
 * @author Even Åby Larsen (even.larsen@uia.no)
 */
public class UserAdmin extends Page implements Constants {
    public static final String SERVLET_NAME = "admin.useradmin";

    @PersistenceUnit(name=PERSISTENCE_UNIT)
    private EntityManagerFactory emf;


    public UserAdmin() {
        super(Role.admin);
    }


    /**
     * Write a user list with links for editing user data.
     * @param out
     * @param request
     */
    public void writeBody(PrintWriter out, HttpServletRequest request) {
        out.println("<h1>User Administration</h1>");
        EntityManager em = emf.createEntityManager();
        Query q = em.createNamedQuery("User.findAll");
        List<User> users = (List<User>)q.getResultList();

        out.println("<table class=\"framed\">");
        out.print("<tr><td>New user</td><td>");
        printLink(out, "[Add]", EditUser.SERVLET_NAME);
        out.println("<td></tr>");

        for (User u: users) {
            out.print("<tr><td>"+u.getUserName()+"</td><td>");
            printLink(out,
                    "[Edit]", EditUser.SERVLET_NAME,
                    UID, String.valueOf(u.getUid()));
            out.print("</td><td>");
            printLink(out,
                    "[Roles]", EditUserRoles.SERVLET_NAME,
                    UID, String.valueOf(u.getUid()));
            out.print("</td><td>");
            printLink(out, "[Delete]", DeleteUser.SERVLET_NAME,
                    UID, String.valueOf(u.getUid()));
            out.println("</td></tr>");
        }

        out.print("<tr><td>New user</td><td>");
        printLink(out, "[Add]", EditUser.SERVLET_NAME);
        out.println("<td></tr>");
        out.println("</table>");
    }

    public final static long serialVersionUID = 1;

}
